package zhuzx.solution.ir;

import java.util.Map;

import org.zhuzx.util.GeneralUtil;

import zhuzx.solution.ir.IrDataHelper.IrUser;

public class IrAdminAdder {
	
	public static void main(String[] args) {
		String name = "余晓璟";//注意：有update语句
		String org = "";
		String msg = addAdmin(name, org);
		IrDataHelper.showResult(msg);
	}
	
	/**
	 * 传入org参数值可以赋予上级部门权限
	 */
	static String addAdmin(String name, String org) {
		IrUser user = IrDataHelper.findUser(name, org);
		if (user == null) {
			return null;
		} else {
			if (GeneralUtil.isBlank(org)) {
				org = user.orgName;//没有指定就默认赋予所在公司的权限，若传入org，则可以赋予更上级部门的权限。
				if (GeneralUtil.isBlank(org)) {
					System.out.println("无法定位所在公司，需要传入org参数。");
					return null;
				}
			}
		}
		String sql = "select t1.id, t1.org_name,"
				+ "t1.administrator_no, t1.administrator_name\n"
				+ "from oa.ir_org_mapping t1 where 1=1"
				+ IrDataHelper.createOrgExp("t1.org_name", org);
		Map<String,String> info = IrDataHelper.queryUnique("addAdmin query org", sql, name);
		if (info == null) {
			return null;
		}
		String recId = info.get("ID");
		String orgName = info.get("ORG_NAME");//这才是公司正名，org参数可能是简写。
		String oldAdminNos = info.get("ADMINISTRATOR_NO");
		String oldAdminNames = info.get("ADMINISTRATOR_NAME");
		if (oldAdminNos.contains(user.id)) {
			return name + "已经是" + orgName + "的管理员，"
					+ "请刷新页面查看、确认。\n"
					+ "注：同一个问题请不要反馈给多个人（或在多个渠道反馈）。";
		}
		String updSql = "update oa.ir_org_mapping set\n"
				+ "\tadministrator_no = '%s,%s',\n\tadministrator_name = '%s,%s',\n"
				+ "\tupdate_user = 'zhuzexiang'"
				+ "\nwhere id = '%s'";
		updSql = String.format(updSql,
				oldAdminNos, user.id, oldAdminNames, user.name, recId);
		IrDataHelper.update("addAdmin update", updSql, name);
		return "已将" + name + "设置为【" + orgName + "】的管理员。";
	}
	
}